package com.culturalCenter.dataCenter.service.impl.activity;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.culturalCenter.dataCenter.Utils.DateFormatUtil;
import com.culturalCenter.dataCenter.Utils.TimeUtil;
import com.culturalCenter.dataCenter.customEntity.CustomServicedNumber;
import com.culturalCenter.dataCenter.customEntity.CustomServicedNumberList;
import com.culturalCenter.dataCenter.customEntity.activity.*;
import com.culturalCenter.dataCenter.customEntity.responseParam.activity.ActivityInfoResponse;
import com.culturalCenter.dataCenter.customEntity.responseParam.activity.ActivityListResponse;
import com.culturalCenter.dataCenter.customEntity.responseParam.activity.ActivityMenuResponse;
import com.culturalCenter.dataCenter.customEntity.responseParam.activity.SmartDisplayResponse;
import com.culturalCenter.dataCenter.customEntity.training.CustomInteractive;
import com.culturalCenter.dataCenter.customEntity.training.CustomParticipationRateRank;
import com.culturalCenter.dataCenter.entity.PaiQiResult;
import com.culturalCenter.dataCenter.entity.activity.*;
import com.culturalCenter.dataCenter.enums.StatusEnum;
import com.culturalCenter.dataCenter.mapper.activity.*;
import com.culturalCenter.dataCenter.mapper.site.SiteMapper;
import com.culturalCenter.dataCenter.param.ActivityEventParam;
import com.culturalCenter.dataCenter.service.activity.ActivityService;
import com.culturalCenter.dataCenter.vo.ActivityEventVo;
import com.culturalCenter.dataCenter.vo.DepartmentDataVo;
import com.culturalCenter.dataCenter.vo.PassengerFlowVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author : weicai
 * @date : 15:59 2020/10/29
 */
@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private ActivityMonthCountMapper activityMonthCountMapper;
    @Resource
    private ActivityDepartmentStatisticsMapper activityDepartmentStatisticsMapper;
    @Resource
    private ActivityTodayMapper activityTodayMapper;
    @Resource
    private ActivityHostMapper activityHostMapper;
    @Resource
    private ActivityPushMapper activityPushMapper;
    @Resource
    private ActivityTypeCountMapper activityTypeCountMapper;
    @Resource
    private ActivityTimeIntervalMapper activityTimeIntervalMapper;
    @Resource
    private ActivityClientCountMapper activityClientCountMapper;
    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private ActivityTodayCountMapper activityTodayCountMapper;
    @Resource
    private ActivityAudienceCountMapper activityAudienceCountMapper;
    @Resource
    private ActivityInfoCountMapper activityInfoCountMapper;
    @Resource
    private ActivityCommentCountMapper activityCommentCountMapper;
    @Resource
    private SiteMapper siteMapper;
    @Resource
    private ActivityRoundMapper activityRoundMapper;

    @Override
    public CustomActivityTodayFinish getTodayFinishActivity() {
        return activityMapper.queryTodayFinishActivity(DateFormatUtil.format(new Date()));
    }

    @Override
    public ActivityMenuResponse getMenu(String branchId, String startDate, String endDate,String type) {
        ActivityMenuResponse activityMenuResponse = new ActivityMenuResponse();
        // 总数
        ActivityMonthCount sum = activityMonthCountMapper.selectAllActivityNum(branchId,type);
        ActivityEventParam eventParam = activityRoundMapper.selectAllActivityEventNum(branchId);
        activityMenuResponse.setActivityYearEventNum(eventParam.getYearEventNum());
        activityMenuResponse.setActivityMonthEventNum(eventParam.getMonthEventNum());
        activityMenuResponse.setActivityDayEventNum(eventParam.getDayEventNum());
        activityMenuResponse.setActivityNum(Optional.ofNullable(sum.getSum()).orElse(0));
        if(StringUtils.isBlank(type)){
            activityMenuResponse.setAvgParticipationRate(activityMapper.getActivityAvgParticipationRate(branchId));
        }
        // 本月活动
        ActivityMonthCount monthCount = activityMonthCountMapper.selectActivityByMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        if (Objects.nonNull(monthCount)) {
            activityMenuResponse.setMonthNum(monthCount.getMonthIncreaseNum());
        }
        // 今日活动数
        ActivityMonthCount todayCount = activityMonthCountMapper.selectActivityByDate(DateUtil.today(), branchId);
        activityMenuResponse.setTodayNum(ObjectUtil.isNotEmpty(todayCount) ? todayCount.getTodayIncreaseNum() : 0);
        // 本月每日活动数
        List<ActivityMonthCount> dayTotalList = activityMonthCountMapper.selectByMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(dayTotalList)) {
            activityMenuResponse.setDayTotalList(dayTotalList);
        }
        LocalDate date = LocalDate.now();
        LocalDate firstDayOfMonth = date.withDayOfMonth(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<ActivityEventVo> activityEventVos = activityRoundMapper.selectAllActivityEventByMonth(branchId);
        while (date.isAfter(firstDayOfMonth) || date.isEqual(firstDayOfMonth)){
            String format = date.format(formatter);
            boolean allContainDate = activityEventVos.stream()
                    .anyMatch(ActivityEventVo -> ActivityEventVo.getBeginTime().equals(format));
            if (!allContainDate){
                ActivityEventVo vo = new ActivityEventVo();
                vo.setBeginTime(format);
                vo.setTodayIncreaseNum(0);
                activityEventVos.add(vo);
            }
            date = date.minusDays(1);
        }
        TimeUtil.timeSort(activityEventVos,ActivityEventVo::getBeginTime,"yyyy-MM-dd");
        activityMenuResponse.setActivityEventVos(activityEventVos);
        // 各部门举办活动数
        List<ActivityDepartmentStatistics> activityNumList = activityDepartmentStatisticsMapper.selectActivityNumByMonth(startDate,endDate, branchId);
        if (CollectionUtils.isNotEmpty(activityNumList)) {
            activityMenuResponse.setActivityNumList(activityNumList);
        }
        // 各部门名额数/报名数/录取数/签到数
//        List<ActivityDepartmentStatistics> activitiesNumList = activityDepartmentStatisticsMapper.selectActivitiesNumByMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        List<DepartmentDataVo> departmentDataVos = activityMapper.selectDepartmentData(startDate,endDate,branchId);
        activityMenuResponse.setDepartmentDataVos(departmentDataVos);
//        if (CollectionUtils.isNotEmpty(activitiesNumList)) {
//            activityMenuResponse.setActivitiesNumList(activitiesNumList);
//        }
        // 今日活动
        List<CustomActivityToday> activityTodayList = activityTodayMapper.selectByDate(DateFormatUtil.format(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(activityTodayList)) {
            activityMenuResponse.setActivityTodayList(activityTodayList);
        }
        // 热门活动排行榜
//        List<ActivityHost> activityHostList = activityHostMapper.selectByMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        List<ActivityHost> activityHostList = activityMapper.selectActivityHost(startDate,endDate,branchId);
        if (CollectionUtils.isNotEmpty(activityHostList)) {
            activityHostList.forEach(val ->{
                double v = Double.parseDouble(Optional.ofNullable(val.getParticipationRate()).orElse("0"));
                double num =1-Math.exp(-v);
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                val.setParticipationRate(decimalFormat.format(num));
            });
            activityMenuResponse.setPopularActivityList(activityHostList);
        }
        // 今日推荐
        List<ActivityPush> activityPushList = activityPushMapper.selectByDate(DateFormatUtil.format(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(activityPushList)) {
            activityMenuResponse.setRecommendTodayList(activityPushList);
        }
        // 本月各分类活动报名人数
        List<ActivityTypeCount> thisMonthNum = activityTypeCountMapper.selectThisMonthByMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(thisMonthNum)) {
            activityMenuResponse.setThisMonthList(thisMonthNum);
        }
        // 上月分类活动报名人数
        List<ActivityTypeCount> lastMonthNum = activityTypeCountMapper.selectLastMonthByMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(lastMonthNum)) {
            activityMenuResponse.setLastMonthList(lastMonthNum);
        }
        // 活动报名时段占比
        List<ActivityTimeInterval> activityTimeIntervalList = activityTimeIntervalMapper.findPageAll(startDate,endDate,branchId);
        if (CollectionUtils.isNotEmpty(activityTimeIntervalList)) {
            activityMenuResponse.setIntervalList(activityTimeIntervalList);
        }
        // 用户活动报名平台入口占比
        /*List<ActivityClientCount> activityClientCountList = activityClientCountMapper.findPageAll(branchId);
        if (CollectionUtils.isNotEmpty(activityClientCountList)) {
            activityMenuResponse.setPlatformsRatioList(activityClientCountList);
        }*/
        // 参与率排行
        List<CustomParticipationRateRank> participationRateRank = activityMapper.selectParticipationRateRank(startDate,endDate,branchId);
        if (CollectionUtils.isNotEmpty(participationRateRank)) {
            activityMenuResponse.setParticipationRateRankList(participationRateRank);
        }
        // 分类参与率排行榜
        List<CustomParticipationRateRank> classifyParticipationRateRank = activityMapper.selectClassifyParticipationRateRank(startDate,endDate, branchId);
        if (CollectionUtils.isNotEmpty(classifyParticipationRateRank)) {
            activityMenuResponse.setClassifyParticipationRateRankList(classifyParticipationRateRank);
        }
        // 可选时间段
        activityMenuResponse.setEarliestDate(DateUtil.format(activityMapper.getEarliestDate(branchId), "yyyy-MM-dd"));
        activityMenuResponse.setLatestDate(DateUtil.today());
        // 服务人群
        Set<String> crowdSet = new HashSet<>();
        List<String> crowdList = activityMapper.getCrowd(branchId, startDate, endDate);
        crowdList.forEach(a -> {
            String[] b = a.split(",");
            Arrays.stream(b).distinct().forEach(bb -> {
                if (ObjectUtil.isNotEmpty(bb)) {
                    crowdSet.add(bb);
                }
            });
        });
        Map<String, Integer> crowdMap = new HashMap<>();
        crowdSet.forEach(crowd -> crowdMap.put(crowd, activityMapper.getNumByCrowd(branchId, crowd, startDate, endDate)));
        if (CollectionUtils.isNotEmpty(crowdList)) {
            activityMenuResponse.setCrowdMap(crowdMap);
        }
        // 艺术分类
        Set<String> artSet = new HashSet<>();
        List<String> artList = activityMapper.getArt(branchId, startDate, endDate);
        if (CollectionUtils.isNotEmpty(artList)) {
            artList.forEach(a -> {
                if (StringUtils.isNotEmpty(a)) {
                    String[] b = a.split("、");
                    Arrays.stream(b).distinct().forEach(bb -> {
                        if (ObjectUtil.isNotEmpty(bb)) {
                            artSet.add(bb);
                        }
                    });
                }
            });
            Map<String, Integer> artMap = new HashMap<>();
            artSet.forEach(art -> artMap.put(art, activityMapper.getNumByArt(branchId, art, startDate, endDate)));
            activityMenuResponse.setArtClassificationMap(artMap);
        }
        // 活动类型
        List<String> activityTypeList = activityMapper.getActivityTypeList(branchId, startDate, endDate);
        Map<String, Integer> activityTypeMap = new HashMap<>();
        activityTypeList.forEach(a -> activityTypeMap.put(a, activityMapper.getNumByActivityType(a, branchId, startDate, endDate)));
        activityMenuResponse.setActivityTypeMap(activityTypeMap);
        // 服务人次：没传日期就查当月的
        List<CustomServicedNumberList> dayServiceNumber = new ArrayList<>();
        Date startDay = DateUtil.parse(ObjectUtil.isEmpty(startDate) ? DateUtil.formatDateTime(DateUtil.beginOfMonth(DateUtil.date())) : startDate, "yyyy-MM-dd");
        Date endDay = DateUtil.parse(ObjectUtil.isEmpty(endDate) ? DateUtil.today() : endDate, "yyyy-MM-dd");
        long difference = DateUtil.between(startDay, endDay, DateUnit.DAY);
        /*
          固定显示10条，没数据的显示为0
           10条及以下：全显示
           10条以上：取开始和结束日期，然后中间的等分取8条
         */
        if (difference < 10) {
            for (int i = 0; i < difference + 1; i++) {
                CustomServicedNumberList customServicedNumberList = new CustomServicedNumberList();
                customServicedNumberList.setDate(DateUtil.offsetDay(startDay, i).toDateStr());
                CustomServicedNumberList servicedNumber = activityMapper.getServicedNumberList(branchId, DateUtil.offsetDay(startDay, i).toSqlDate());
                if (ObjectUtil.isNull(servicedNumber)) {
                    customServicedNumberList.setOfflineNumber(0);
                    customServicedNumberList.setOnlineNumber(0);
                } else {
                    customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                    customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
                }
                dayServiceNumber.add(customServicedNumberList);
            }
        } else {
            // 起始
            CustomServicedNumberList customServicedNumberList = new CustomServicedNumberList();
            customServicedNumberList.setDate(DateUtil.formatDate(startDay));
            CustomServicedNumberList servicedNumber = activityMapper.getServicedNumberList(branchId, startDay);
            if (ObjectUtil.isNull(servicedNumber)) {
                customServicedNumberList.setOfflineNumber(0);
                customServicedNumberList.setOnlineNumber(0);
            } else {
                customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
            }
            dayServiceNumber.add(customServicedNumberList);
            // 中间
            for (int i = 1; i < 9; i++) {
                customServicedNumberList = new CustomServicedNumberList();
                customServicedNumberList.setDate(DateUtil.offsetDay(startDay, (int) ((difference + 1) / 10 * i)).toDateStr());
                servicedNumber = activityMapper.getServicedNumberList(branchId, DateUtil.offsetDay(startDay, (int) ((difference + 1) / 10 * i)).toSqlDate());
                if (ObjectUtil.isNull(servicedNumber)) {
                    customServicedNumberList.setOfflineNumber(0);
                    customServicedNumberList.setOnlineNumber(0);
                } else {
                    customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                    customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
                }
                dayServiceNumber.add(customServicedNumberList);
            }
            // 结束
            customServicedNumberList = new CustomServicedNumberList();
            customServicedNumberList.setDate(DateUtil.formatDate(endDay));
            servicedNumber = activityMapper.getServicedNumberList(branchId, endDay);
            if (ObjectUtil.isNull(servicedNumber)) {
                customServicedNumberList.setOfflineNumber(0);
                customServicedNumberList.setOnlineNumber(0);
            } else {
                customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
            }
            dayServiceNumber.add(customServicedNumberList);
        }
        activityMenuResponse.setServiceNumberList(dayServiceNumber);
        // 服务人次统计
        CustomServicedNumber servicedNumber = activityMapper.getServicedNumber(branchId, startDay, endDay);
        if (ObjectUtil.isNull(servicedNumber)) {
            servicedNumber= new CustomServicedNumber();
            servicedNumber.setTotal(0);
            servicedNumber.setOnlineNumber(0);
            servicedNumber.setOfflineNumber(0);
        }
        activityMenuResponse.setServicedNumber(servicedNumber);

        return activityMenuResponse;
    }

    @Override
    public ActivityListResponse getActivityList(String activityName, String status, String branchId, int pageNum, int pageSize) {
        ActivityListResponse activityListResponse = new ActivityListResponse();
        // 获取各个状态下的活动数量
        ActivityTodayCount activityStatusCount = activityMapper.activityStatusCount(branchId);
//        List<ActivityTodayCount> activityList = activityTodayCountMapper.getActivities(branchId);
//        if (CollectionUtils.isNotEmpty(activityList) && activityList.get(0) != null) {
//            activityList.forEach(a -> {
//                if (a.getTrailer() != null) {
//                    activityListResponse.setTrailer(a.getTrailer());
//                }
//                if (a.getSigningUp() != null) {
//                    activityListResponse.setSigningUp(a.getSigningUp());
//                }
//                if (a.getProcessing() != null) {
//                    activityListResponse.setProcessing(a.getProcessing());
//                }
//                if (a.getOver() != null) {
//                    activityListResponse.setOver(a.getOver());
//                }
//                if (a.getSum() != null) {
//                    activityListResponse.setTotal(a.getSum());
//                }
//            });
//        }
        activityListResponse.setTrailer(activityStatusCount.getTrailer());
        activityListResponse.setSigningUp(activityStatusCount.getSigningUp());
        activityListResponse.setProcessing(activityStatusCount.getProcessing());
        activityListResponse.setOver(activityStatusCount.getOver());
        activityListResponse.setTotal(activityStatusCount.getSum());
        // 列表、搜索
        Integer status1 = StatusEnum.getStatusId(status);
        PageHelper.startPage(pageNum, pageSize);
        List<CustomActivityList> customActivityList = activityMapper.getAllActivity(activityName, status1, branchId);
        PageInfo<CustomActivityList> pageInfo = new PageInfo<>(customActivityList);
        activityListResponse.setPageInfo(pageInfo);
        return activityListResponse;
    }

    @Override
    public ActivityInfoResponse getActivityInfo(String activityId) {
        ActivityInfoResponse activityInfoResponse = new ActivityInfoResponse();
        Activity activity = activityMapper.queryInfoByActivityId(activityId);
        if (Objects.nonNull(activity)) {
            activityInfoResponse.setId(activity.getId());
            activityInfoResponse.setPicture(activity.getPicture());
            activityInfoResponse.setActivityName(activity.getActivityName());
            activityInfoResponse.setActivityLabel(activity.getActivityLabel());
            activityInfoResponse.setStatus(activity.getStatus());
            activityInfoResponse.setOrganizationUnit(activity.getDepartment());
            activityInfoResponse.setContacts(activity.getContacts());
            activityInfoResponse.setActivityBeginTime(activity.getBeginTime());
            activityInfoResponse.setActivityEndTime(activity.getEndTime());
        }

        // 人群特征
        List<CustomActivityStatistic> characteristicsList = activityAudienceCountMapper.queryInfoByActivityId(activityId);
        if (CollectionUtils.isNotEmpty(characteristicsList)) {
            characteristicsList.forEach(gender -> {
                // 求报名人数最多的性别和比例
                if (gender.getMaleNum() > gender.getFemaleNum()) {
                    gender.setGeneration("男");
                    gender.setGenerationRate(gender.getMaleRate());
                } else {
                    gender.setMostGender("女");
                    gender.setMostGenderRate(gender.getFemaleRate());
                }
                // 求报名人数最多的年龄段和比例
                List<Integer> listAge = new ArrayList<>();
                listAge.add(gender.getAge1());
                listAge.add(gender.getAge2());
                listAge.add(gender.getAge3());
                listAge.add(gender.getAge4());
                listAge.add(gender.getAge5());
                listAge.add(gender.getAge6());
                listAge.add(gender.getAge7());
                listAge.add(gender.getAge8());
                Integer maxAgeNum = listAge.stream().max(Integer::compareTo).get();// 报名人数最多的年龄段的人数
                Integer totalNum = gender.getAge1() + gender.getAge2() + gender.getAge3() + gender.getAge4()
                        + gender.getAge5() + gender.getAge6() + gender.getAge7() + gender.getAge8();// 报名总数
                if (totalNum != 0) {
                    if (maxAgeNum == gender.getAge1()) {
                        gender.setGeneration("6-12");
                        // 报名人数最多的年龄区间比例（结果保留2位小数）
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                    if (maxAgeNum == gender.getAge2()) {
                        gender.setGeneration("13-19");
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                    if (maxAgeNum == gender.getAge3()) {
                        gender.setGeneration("20-24");
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                    if (maxAgeNum == gender.getAge4()) {
                        gender.setGeneration("25-30");
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                    if (maxAgeNum == gender.getAge5()) {
                        gender.setGeneration("31-40");
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                    if (maxAgeNum == gender.getAge6()) {
                        gender.setGeneration("41-50");
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                    if (maxAgeNum == gender.getAge7()) {
                        gender.setGeneration("51-60");
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                    if (maxAgeNum == gender.getAge8()) {
                        gender.setGeneration("60以上");
                        gender.setGenerationRate(String.valueOf(new BigDecimal((float) maxAgeNum / totalNum * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                    }
                }
            });
            activityInfoResponse.setCharacteristicsList(characteristicsList);
        }

        // 参与情况
        List<ActivityInfoCount> participateList = activityInfoCountMapper.queryByActivityId(activityId);
        if (CollectionUtils.isNotEmpty(participateList)) {
            /*participateList.forEach(p -> {
                if (p.getAirborneNum() < 0) {
                    p.setAirborneNum(0);
                }
            });*/
            activityInfoResponse.setParticipateList(participateList);
        }

        // 点击数据
        List<ActivityInfoCount> browseList = activityInfoCountMapper.selectBrowseNum(activityId);
        if (CollectionUtils.isNotEmpty(browseList)) {
            activityInfoResponse.setBrowseList(browseList);
        }

        // 互动
        List<CustomInteractive> interactiveList = activityCommentCountMapper.queryByActivityId(activityId);
        if (CollectionUtils.isNotEmpty(interactiveList) && interactiveList.get(0) != null) {
            int numJoin = participateList.stream().mapToInt(ActivityInfoCount::getAttendance).sum();
            interactiveList.forEach(interactive -> {
                if (numJoin == 0) {
                    interactive.setCommentRate(0.0);
                } else if (interactive.getCommentNum() > numJoin) {
                    interactive.setCommentRate(100.0);
                } else {
                    DecimalFormat df = new DecimalFormat("0.00");
                    interactive.setCommentRate(Double.valueOf(df.format(interactive.getCommentNum() / numJoin * 100)));
                }
            });
            activityInfoResponse.setInteractiveList(interactiveList);
        }
        return activityInfoResponse;
    }

    @Override
    public Activity getActivityInfoDetail(String activityId) {
        return activityMapper.queryById(activityId);
    }

    @Override
    public List<Activity> getAllActivityByBranchId() {

        return activityMapper.getAllActivityByBranchId();
    }

    @Override
    public CustomSiteActivity getActivityBySiteCode(String siteCode) {
        CustomSiteActivity customSiteActivity = siteMapper.selectBySiteCode(siteCode);
//        List<PaiQiResult> activityList = activityMapper.getActivityScreenInfoBySiteCode(siteCode, DateFormatUtil.format(new Date()));
        //查询近一周的场地预约数据
        List<PaiQiResult> activityList = activityMapper.getNewActivityScreenInfoBySiteCode(siteCode, DateFormatUtil.format(new Date()));
        if (CollectionUtils.isNotEmpty(activityList)) {
            customSiteActivity.setActivityList(activityList);
        }
        return customSiteActivity;
    }

    @Override
    public List<Activity> getActivityByStatus() {
        return activityMapper.getActivityByStatus();
    }

    @Override
    public SmartDisplayResponse getSmartDisplayInformation(String branchId) {

        SmartDisplayResponse smartDisplayResponse = new SmartDisplayResponse();
        smartDisplayResponse.setVisitors(1736);
        smartDisplayResponse.setInTheLibrary(1322);
        smartDisplayResponse.setEvents(activityMapper.getEvents(branchId));
        smartDisplayResponse.setTrainings(activityMapper.getTrainings(branchId));
        smartDisplayResponse.setInformation(activityMapper.getInformation(branchId));
        smartDisplayResponse.setServiceVisits(activityMapper.getServiceVisits(branchId));
        smartDisplayResponse.setRegisteredUsers(activityMapper.setRegisteredUsers(branchId));
        smartDisplayResponse.setVolunteers(activityMapper.getVolunteers(branchId));
        List<CustomActivitySmartScreen> activitiesTheMonth = activityMapper.getActivitiesTheMonth(branchId);
        activityDateFormatting(activitiesTheMonth);
        smartDisplayResponse.setActivitiesTheMonth(activitiesTheMonth);
        List<CustomActivitySmartScreen> activitiesNextMonth = activityMapper.getActivitiesNextMonth(branchId);
        activityDateFormatting(activitiesNextMonth);
        smartDisplayResponse.setActivitiesNextMonth(activitiesNextMonth);
        smartDisplayResponse.setWonderfulMoment(activityMapper.selectActivityPicture(branchId));
        return smartDisplayResponse;
    }

    private void activityDateFormatting(List<CustomActivitySmartScreen> activitiesNextMonth) {
        activitiesNextMonth.forEach(a -> {
            List<CustomActivityRoundTime> roundTime = activityMapper.getRoundTimeById(a.getId());
            StringBuilder period = new StringBuilder();
            for (CustomActivityRoundTime c : roundTime) {
                period.append(' ').append(c.getPeriod());
            }
            String[] maxDayByYear = roundTime.get(0).getMaxDay().split("年");
            String[] maxDayByMonth = roundTime.get(0).getMaxDay().split("月");

            if (roundTime.get(0).getMaxDay().equals(roundTime.get(0).getMinDay())) {
                a.setActivityTime(roundTime.get(0).getMinDay() + period);
            } else if (roundTime.get(0).getMinDay().contains(maxDayByMonth[0])) {
                a.setActivityTime(roundTime.get(0).getMinDay() + "至" + maxDayByMonth[1] + period);
            } else if (roundTime.get(0).getMinDay().contains(maxDayByYear[0])) {
                a.setActivityTime(roundTime.get(0).getMinDay() + "至" + maxDayByYear[1] + period);
            } else {
                a.setActivityTime(roundTime.get(0).getMinDay() + "至" + roundTime.get(0).getMaxDay() + period);
            }
        });
    }

    @Override
    public List<Activity> getNavigationScreen(String branchId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return activityMapper.getNewNavigationScreen(branchId);
//        return activityMapper.getNavigationScreen(branchId);
    }

}
